﻿# Create your views here.
from django.template.loader import get_template
from django.template import Context,RequestContext

from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.conf import settings

import traceback,sys

#Ajax new implementation
from django.utils import simplejson
import MySQLdb

#from time import localtime, strptime, strftime, mktime
from time import strptime
from datetime import datetime, timedelta
#from django.contrib.auth.models import User

def get_time_diference():
	#date_now = datetime.now() - timedelta(minutes=(0)) #gmtoffset
	date_now = datetime.now()
	timeTuple1 = strptime("2010-07-26 14:00","%Y-%m-%d %H:%M")
	#timeTuple2 = localtime()
	#time_difference = mktime(timeTuple2) - mktime(timeTuple1)
	dt_obj = datetime(*timeTuple1[0:6])
	
	#time_difference = mktime(timeTuple2) - mktime(timeTuple1)
	time_difference = date_now - dt_obj
	
	#return HttpResponse(simplejson.dumps({'time_diff':str( int((time_difference.days*86400+time_difference.seconds)/3600.0) )}), mimetype='application/json; charset=UTF-8')
	#return time_difference
	return str( int((time_difference.days*86400+time_difference.seconds)/60) )

def get_grid_test(request):
	db = MySQLdb.connect(user = settings.STOCKS_DB_USER, 
						db = settings.STOCKS_DB_NAME, 
						passwd = settings.STOCKS_DB_PASS, 
						host = settings.STOCKS_DB_HOST, 
						port = settings.STOCKS_DB_PORT)
	
		
	#date_now = datetime.now() - timedelta(minutes=(0)) #gmtoffset
	#timeTuple1 = strptime("2010-07-26 10:00","%Y-%m-%d %H:%M")
	#dt_obj = datetime(*timeTuple1[0:6])
	#time_difference = date_now - dt_obj
		
	#DEV
	time_difference_hour = get_time_diference()
	query_select = """
					SELECT DISTINCT `ativo_cod`, CONCAT(FORMAT((((ultimo*100)/abertura)-100),2),'%%') `porc`, `abertura`, `max`, `min`, `ultimo`, `oferta_compra`, `volume`, `min_forever`, CONCAT(`max_forever`,'#')
					FROM br_stocks_prod
					WHERE data_hora = (
					SELECT data_hora
					FROM br_stocks_prod
					WHERE data_hora < DATE_SUB(CURRENT_TIMESTAMP(), INTERVAL %s HOUR)
					ORDER BY data_hora DESC
					LIMIT 1) ORDER BY data_hora DESC
					""" % (time_difference_hour)
	cursor = db.cursor()
	cursor.execute(query_select)
	response = cursor.fetchall()
	db.close()
	#return HttpResponse(json.dumps(response, sort_keys=True))
	return HttpResponse(simplejson.dumps(response), mimetype='application/json; charset=UTF-8')


def get_mydb_test(template_name='monitor_test.html'):
	try:
		db = MySQLdb.connect(user = settings.STOCKS_DB_USER, 
						db = settings.STOCKS_DB_NAME, 
						passwd = settings.STOCKS_DB_PASS, 
						host = settings.STOCKS_DB_HOST, 
						port = settings.STOCKS_DB_PORT)
		cursor = db.cursor()
		cursor.execute("""
						SELECT DISTINCT `ativo_cod`, CONCAT(FORMAT((((ultimo*100)/abertura)-100),2),'%') `porc`, `abertura`, `max`, `min`, `ultimo`, `oferta_compra`, `volume`, `min_forever`, `max_forever`
						FROM br_stocks_prod
						WHERE data_hora = (
						SELECT data_hora
						FROM br_stocks_prod
						ORDER BY data_hora DESC
						LIMIT 1) ORDER BY data_hora DESC
						""")
		response_dict = {}
		response_dict['response'] = cursor.fetchall()
		response_dict['fields'] = cursor.description
		response_dict['fields_abr'] = []
		for v in cursor.description:
			str_field_nme = str(v[0])
			response_dict['fields_abr'].append(str_field_nme.replace("_","").replace(" ","").upper()[:3])
		db.close()
		
		#adding template name
		response_dict['template_name'] = template_name
		
		#print response_dict
		
		#t = get_template('two_columns_url.html')
		#c = RequestContext(request,response_dict)
		#html = t.render(c)
		#return HttpResponse(html, mimetype='text/html; charset=UTF-8')
		return response_dict
	except:
		exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
		traceback.print_exception(exceptionType, exceptionValue, exceptionTraceback,
						  limit=2, file=sys.stdout) 

def get_monitor_ajax(request):
	try:
		response_dict=get_mydb_test()
		t = get_template(response_dict['template_name'])
		c = RequestContext(request,response_dict)
		html = t.render(c)
		return HttpResponse(html, mimetype='text/html; charset=UTF-8')
	except:
		exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
		traceback.print_exception(exceptionType, exceptionValue, exceptionTraceback,
						  limit=2, file=sys.stdout) 
		
def get_principal(request):
	return render_to_response('principal_temp.html')

def get_home(request):
	return render_to_response('content_temp.html')

